<template>
  <view class="container">
    <!-- 顶部图片 -->
    <view class="top-image">
      <image src="/static/tabbar/logo.png" mode="aspectFill" />
    </view>

    <!-- 轮播图区域 -->
    <view class="swiper-section">
      <swiper
        class="custom-swiper"
        autoplay
        circular
        :indicator-dots="true"
        indicator-active-color="#ff6b6b"
      >
        <swiper-item v-for="item in list2" :key="item.id">
          <image :src="item.image" mode="aspectFill" class="swiper-image" />
        </swiper-item>
      </swiper>
    </view>

    <!-- 商品展示区 -->
    <view class="product-section">
      <view class="product-card">
        <!-- 商品图片 -->
        <image class="product-image" :src="formData.pic" mode="aspectFill" />

        <!-- 商品信息 -->
        <view class="product-info">
          <!-- 价格信息 -->
          <view class="price-row">
            <text class="price-label">单价</text>
            <text class="price-value"
              >{{ formData.price }}<text class="unit">积分</text></text
            >
          </view>

          <!-- 剩余数量 -->
          <view class="stock-row">
            <text class="stock-label">剩余数量</text>
            <text class="stock-value"
              >{{ formData.total }}<text class="unit">张</text></text
            >
          </view>

          <!-- 购买数量 -->
          <view class="amount-row">
            <text class="amount-label">购买数量</text>
            <input
              class="amount-input"
              type="number"
              v-model="buyNum"
              placeholder="请输入购买数量"
              @input="onNumberInput"
            />
          </view>

          <!-- 总价 -->
          <view class="total-row">
            <text class="total-label">总积分</text>
            <text class="total-value"
              >{{ formData.price * (buyNum || 1)
              }}<text class="unit">积分</text></text
            >
          </view>
        </view>

        <!-- 购买按钮 -->
        <view class="button-group">
          <button class="transfer-button" @click="onBuyClick">立即兑换</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import authApi from "@/asstes/api/auth";
import goodsApi from "@/asstes/api/goods";
import { API_CONFIG } from "@/asstes/api/config/api.config";

export default {
  name: "Index",
  data() {
    return {
      list2: [],
      formData: {},
      loading: false,
      userInfo: null,
      balance: 0,
      buyNum: 1,
      canBuy: true,
      socket: null,
      messages: [],
      heartbeatTimer: null
    };
  },
  onLoad() {
    // socket连接
    this.connectWebSocket();
    const userInfo = JSON.parse(localStorage.getItem("userInfo"));
    console.log("userInfo", userInfo);
    if (userInfo) {
      this.userInfo = userInfo;
      this.fetchUserInfo();
      this.fetchCardList();
    }
    // 获取轮播图
    this.getCarousel()

  },
  onUnload() {
    if (this.socket) {
      this.socket.close();
    }
    if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
  },
  methods: {
    async getCarousel() { 
      const res = await goodsApi.banner();
     console.log("res",res)

    },
    connectWebSocket() {
      // 定时发送心跳
      this.heartbeatTimer = setInterval(() => {
        if (this.socket.readyState === this.socket.OPEN) {
          this.socket.send({
            data: 'ping'
          });
        }
      }, 30000);
      // 动态判断环境（开发环境可能需代理）
      const isDev = process.env.NODE_ENV === 'development';
      const wsUrl = isDev ? 'ws://www.pc.sanhuijucai.com/ws/message' : 'wss://your-domain.com/ws/message';
      
      this.socket = uni.connectSocket({
        url: wsUrl,
        success: () => {
          console.log('WebSocket 连接初始化');
        }
      });

      // 监听事件
      this.socket.onOpen(() => {
        console.log('WebSocket 连接成功');
        // 发送认证信息（若需要）
        this.socket.send({
          data: JSON.stringify({ type: 'auth', token: '用户token' })
        });
      });

      this.socket.onMessage((res) => {
        if (res.data !== "pong") {
            const message = JSON.parse(res.data);
            console.log("接收到消息：", message)
            if (message.price) { 
              if (this.formData.price != message.price) { 
                this.formData.price = message.price;
                uni.showModal({
                  title: "价格已变动",
                  content: `确定要继续购买吗？价格：${message.price}元`,
                  success: (res) => {
                    console.log("res", res);
                    if (res.confirm) {
                      console.log("用户点击确定购买卡片");
                      this.purchaseCard();
                    } else { 
                      uni.showToast({
                        title: "您已取消兑换",
                        type: "none"
                      })
                    }
                  },
                });
                return
              }
            }
            if (message.freezeStatus) { 
                console.log("freezeStatus",message.freezeStatus)
                uni.showModal({
                  title: "账户异常通知",
                  content: `该账户已被冻结，无法进行交易`,
                  success: (res) => {
                    console.log("res", res);
                    if (res.confirm) {  
                      console.log("用户点击确定");
                    }
                  },
                });
                return
            }
         }
      });

      this.socket.onError((err) => {
        console.error('WebSocket 错误:', err);
        // 断线重连
        setTimeout(() => this.connectWebSocket(), 3000);
      });

      this.socket.onClose(() => {
        console.log('WebSocket 连接关闭');
      });
    },
    async fetchUserInfo() {
      try {
        const data = {
          userId: 0,
          sysUserId: this.userInfo.userId,
        };
        const response = await authApi.getUserInfo(data);
        console.log("用户信息:", response);
        if (response.code === 200) {
          if (response.user) {
            this.userInfo = response.user;
            this.balance = response.user.balance || 0;
          }
        }
      } catch (error) {
        console.error("获取用户信息失败:", error);
        uni.showToast({
          title: "获取用户信息失败",
          icon: "none",
        });
      }
    },
    async fetchCardList() {
      try {
        this.loading = true;
        const res = await goodsApi.list();
        if (res.code === 200 && res.rows.length > 0) {
          res.rows[0].pic = API_CONFIG.BASE_URL + res.rows[0].pic;
          this.formData = res.rows[0];
        }
      } catch (error) {
        console.error("获取卡片列表失败:", error);
        uni.showToast({
          title: "获取卡片列表失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },
    handlePurchase(e) {
      const { id, price } = e.currentTarget.dataset;
      if (this.balance < price) {
        uni.showToast({
          title: "余额不足",
          icon: "none",
        });
        return;
      }

      uni.showModal({
        title: "确认兑换",
        content: `确定要兑换这张卡片吗？价格：${price}元`,
        success: (res) => {
          console.log("res", res);
          if (res.confirm) {
            console.log("用户点击确定兑换卡片");
            this.purchaseCard();
          }
        },
      });
    },
    async purchaseCard() {
      try {
        uni.showLoading({
          title: "购买中...",
          mask: true,
        });

        const data = {
          shopId: this.formData.shopId,
          userId: this.userInfo.userId,
          cardCount: this.buyNum,
          price: this.formData.price,
          totalAmount: this.formData.price * this.buyNum,
        };

        const res = await goodsApi.create(data);

        if (res.code === 200) {
          uni.showToast({
            title: "购买成功",
            icon: "success",
          });
          setTimeout(() => {
            this.balance = this.balance - this.formData.price * this.buyNum;
            this.fetchUserInfo();
            this.fetchCardList();
          }, 1000);
        } else {
          throw new Error(res.msg || "购买失败");
        }
      } catch (error) {
        console.error("购买失败:", error);
        uni.showToast({
          title: error.message || "购买失败，请重试",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },
    handleRecharge() {
      uni.navigateTo({
        url: "/pages/recharge/index",
      });
    },
    onNumberInput(e) {
      const value = e.detail.value;

      if (value === "") {
        this.buyNum = "";
        this.canBuy = false;
        return;
      }

      if (!/^\d+$/.test(value)) {
        uni.showToast({
          title: "请输入正整数",
          icon: "none",
        });
        this.buyNum = 1;
        this.canBuy = true;
        return;
      }

      const num = parseInt(value);

      if (num > this.formData.total) {
        uni.showToast({
          title: "超过可购买数量",
          icon: "none",
        });
        this.buyNum = num;
        this.canBuy = false;
        return;
      }

      if (num <= 0) {
        uni.showToast({
          title: "请输入正确的购买数量",
          icon: "none",
        });
        this.buyNum = 1;
        this.canBuy = true;
        return;
      }

      this.buyNum = num;
      this.canBuy = true;
    },
    async onBuyClick() {
      // 继续购买逻辑
      if (this.buyNum === "") {
        uni.showToast({
          title: "请输入购买数量",
          icon: "none",
        });
        return;
      }

      if (!this.canBuy) {
        uni.showToast({
          title: "购买数量超过限制",
          icon: "none",
        });
        return;
      }

      if (!this.userInfo) {
        uni.showToast({
          title: "请先登录",
          icon: "none",
        });
        return;
      }

      const totalPrice = this.formData.price * this.buyNum;
      if (this.balance < totalPrice) {
        uni.showToast({
          title: "余额不足",
          icon: "none",
        });
        return;
      }

      uni.showModal({
        title: "确认兑换",
        content: `确定要兑换 ${this.buyNum} 张卡片吗？\n总价：${totalPrice}SHJC积分`,
        success: (res) => {
          if (res.confirm) {
            this.submitPurchase();
          }
        },
      });
    },
    async submitPurchase() {
      try {
        uni.showLoading({
          title: "兑换中...",
          mask: true,
        });
        console.log("this.userInfo", this.userInfo);

        const data = {
          shopId: this.formData.shopId,
          userId: this.userInfo.userId,
          cardCount: this.buyNum,
          price: this.formData.price,
          totalAmount: this.formData.price * this.buyNum,
        };

        const res = await goodsApi.create(data);

        console.log("res",res)

        if (res.code === 200) {
          uni.showToast({
            title: "购买成功",
            icon: "success",
          });

          setTimeout(() => {
            this.fetchUserInfo();
            this.fetchCardList();

            this.buyNum = 1;
          }, 1000);
        } else {
          throw new Error(res.msg || "购买失败");
        }
      } catch (error) {
        console.error("购买失败:", error);
        uni.showToast({
          title: error.msg || "购买失败，请重试",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },
    async handleLogout() {
      try {
        await authService.logout();
        // 使用 uni 的导航方法
        uni.reLaunch({
          url: "/pages/login/index",
          success: () => {
            console.log("退出成功");
          },
          fail: (error) => {
            console.error("跳转失败:", error);
          },
        });
      } catch (error) {
        console.error("退出登录失败:", error);
        // 即使退出失败，也跳转到登录页
        uni.reLaunch({
          url: "/pages/login/index",
        });
      }
    },
  },
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #ffffff;
  padding: 40rpx 30rpx;
}

.top-image {
  width: 100px;
  height: 100px;
  margin: auto;
  display: flex;
  justify-content: center;
  align-items: center;
}

.top-image image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

/* 顶部导航栏 */
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px; /* 88rpx -> 44px */
  /* background: #ffffff; */
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15px; /* 30rpx -> 15px */
  z-index: 100;
  border-bottom: 1px solid #e0e0e0; /* 1rpx -> 1px */
}

.title {
  font-size: 16px; /* 32rpx -> 16px */
  font-weight: 500;
  color: #333;
  letter-spacing: 0.5px; /* 1rpx -> 0.5px */
}

/* 轮播图区域 */
.swiper-section {
  margin-top: 10px; /* 88rpx -> 44px */
  padding: 10px; /* 20rpx -> 10px */
}

.custom-swiper {
  height: 150px; /* 300rpx -> 150px */
  border-radius: 6px; /* 12rpx -> 6px */
  overflow: hidden;
  border: 1px solid #e0e0e0; /* 1rpx -> 1px */
}

.swiper-image {
  width: 100%;
  height: 100%;
}

/* 商品展示区 */
.product-section {
  padding: 0 0px;
}

.section-header {
  margin: 10px 0; /* 20rpx -> 10px */
  padding-bottom: 10px; /* 20rpx -> 10px */
  border-bottom: 1px solid #e0e0e0; /* 1rpx -> 1px */
}

.section-title {
  font-size: 15px; /* 30rpx -> 15px */
  font-weight: 500;
  color: #333;
  letter-spacing: 0.5px; /* 1rpx -> 0.5px */
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 20px; /* 20rpx -> 10px */
}

.product-card {
  background: #ffffff;
  border-radius: 6px; /* 12rpx -> 6px */
  overflow: hidden;
  transition: all 0.3s ease;
}

.product-card:active {
  background: #f8f8f8;
}

.product-image {
  width: 100%;
  height: 150px; /* 300rpx -> 150px */
  background: #ffffff;
  border-bottom: 1px solid #e0e0e0; /* 1rpx -> 1px */
}

.product-info {
  padding: 10px; /* 20rpx -> 10px */
  border: 1px solid #eee;
}

.price-row,
.stock-row,
.amount-row {
  margin: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
}
.total-row {
  margin: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  border-bottom: none;
}

.price-label,
.stock-label,
.amount-label,
.total-label {
  color: #666;
  font-size: 14px;
}

.price-value,
.total-value {
  color: #333;
  font-weight: 500;
}

.stock-value {
  color: #333;
}

.unit {
  font-size: 12px; /* 24rpx -> 12px */
  margin-left: 2px; /* 4rpx -> 2px */
  color: #999;
}

.amount-input {
  /* width: 120px;
  height: 30px; */
  /* border: none; */
  text-align: right;
  font-size: 14px;
  color: #333;
}

.buy-btn {
  width: 100%;
  height: 40px; /* 80rpx -> 40px */
  line-height: 40px; /* 80rpx -> 40px */
  background: #ffffff;
  color: #333;
  font-size: 15px; /* 30rpx -> 15px */
  border-radius: 4px; /* 8rpx -> 4px */
  margin-top: 10px; /* 20rpx -> 10px */
  border: 1px solid #333; /* 1rpx -> 1px */
  transition: all 0.3s ease;
}

.buy-btn:active {
  background: #f5f5f5;
}

/* 底部导航栏 */
.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px; /* 100rpx -> 50px */
  background: #ffffff;
  display: flex;
  justify-content: space-around;
  align-items: center;
  border-top: 1px solid #e0e0e0; /* 1rpx -> 1px */
  padding-bottom: env(safe-area-inset-bottom);
}

.tab-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  font-size: 12px; /* 24rpx -> 12px */
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #333;
}

.tab-item image {
  width: 24px; /* 48rpx -> 24px */
  height: 24px; /* 48rpx -> 24px */
  margin-bottom: 2px; /* 4rpx -> 2px */
  opacity: 0.8;
}

/* 底部按钮样式 */
.button-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px; /* 20rpx -> 10px */
  background: #ffffff;
  border-top: 1px solid #e0e0e0; /* 1rpx -> 1px */
  z-index: 99;
  padding-bottom: calc(10px + env(safe-area-inset-bottom)); /* 20rpx -> 10px */
}

.button-group {
  display: flex;
  gap: 10px; /* 20rpx -> 10px */
}

.transfer-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  color: #fff;
  background: #333;
  border: 1px solid #333;
  border-radius: 4rpx;
  margin-top: 30px;
}

.transfer-button:active {
  background: #f5f5f5;
  color: #fff;
}
</style>
